package util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Random;

public class Util {

    public static int getRandomNum(int min,int max){
        return  new Random().nextInt(max-min) + min;
    }

    public static int getUnusePort(String host){
        int port = 65535;
        for(int i=0;i<100;i++){
            int n = getRandomNum(10000,65535);
            if(isPortUsing(host,n)){
                port = n;
                break;
            }
        }
        return port;
    }

    public static boolean isPortUsing(String host,int port) {
        boolean flag = false;
        try {
            InetAddress theAddress = InetAddress.getByName(host);
            Socket socket = new Socket(theAddress,port);
            flag = true;
        } catch (IOException e) {
            flag = false;
        }
        return flag;
    }

    public static boolean isExpression(String expression){
        if(expression.startsWith("cmd:") || expression.startsWith("code:")){
            return true;
        }else{
            return false;
        }
    }


    public static void main(String[] args) {
        int port = getUnusePort("127.0.0.1");
        System.out.println(port);
    }
}
